package com.course.server.service;

import com.course.server.domain.Chapter;
import com.course.server.domain.ChapterExample;
import com.course.server.dto.ChapterDTO;
import com.course.server.dto.PageDTO;
import com.course.server.mapper.ChapterMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    public void list(PageDTO pageDTO){

        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        //分页规则：调用startPage方法后，下面遇到的第一条select语句会进行分页
        ChapterExample chapterExample = new ChapterExample();

        List<Chapter> chapters = chapterMapper.selectByExample(chapterExample);

        PageInfo<Chapter> pageInfo = new PageInfo<>(chapters);

        pageDTO.setTotal(pageInfo.getTotal());

        ArrayList<ChapterDTO> chapterDTOList = new ArrayList<>();

        for (int i = 0; i < chapters.size(); i++) {
            Chapter chapter = chapters.get(i);
            ChapterDTO chapterDTO = new ChapterDTO();
            BeanUtils.copyProperties(chapter, chapterDTO);
            chapterDTOList.add(chapterDTO);
        }
        pageDTO.setList(chapterDTOList);
    }

    public void save(ChapterDTO chapterDTO){
        Chapter chapter = CopyUtil.copy(chapterDTO, Chapter.class);
        if (StringUtils.isEmpty(chapterDTO.getId())){
            //前端没有带过来id，则是新增
            this.insert(chapter);
        }else{
            this.update(chapter);
        }
    }

    private void insert(Chapter chapter){
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }

    private void update(Chapter chapter){
        chapterMapper.updateByPrimaryKey(chapter);
    }

    public void delete(String id){
        chapterMapper.deleteByPrimaryKey(id);
    }


}
